﻿
@{
    ViewBag.Title = "BuyProduct";
    Layout = "~/Views/Shared/_Layout_iframe.cshtml";
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>产品购买</title>
    <style>
        .search-container {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 15px;
            background: #fff;
        }

        .search-box {
            display: flex;
            align-items: center;
        }

            .search-box .layui-form-item {
                margin-bottom: 0;
            }

        #selectedList {
            margin: 20px;
            padding: 15px;
            background: #fff;
            display: none;
        }
    </style>
</head>
<body>
    <div class="search-container">
        <!-- 搜索框 -->
        <div class="search-box">
            <div class="layui-form">
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">产品名称</label>
                        <div class="layui-input-inline">
                            <input type="text" id="productSearch" placeholder="请输入产品名称" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- 确认选择按钮 -->
        <script type="text/html" id="toolbarDemo">
            <div class="layui-btn-container">
                <button class="layui-btn" lay-event="confirm">确认选择</button>
            </div>
        </script>
    </div>
    <!-- 产品表格 -->
    <table class="layui-hide" id="productTable" lay-filter="productTable"></table>
    <!-- 已选商品清单 -->
    <div id="selectedList">
        <h3>已选商品清单</h3>
        <form class="layui-form" id="buyForm">
            <table class="layui-table">
                <thead>
                    <tr>
                        <th>产品名称</th>
                        <th>库存数量</th>
                        <th>零售价格</th>
                        <th>购买数量</th>
                    </tr>
                </thead>
                <tbody id="selectedItems"></tbody>
            </table>
            <div style="padding: 15px; text-align: right;">
                <span style="font-size: 18px; font-weight: bold;">总计: ￥<span id="totalPrice">0.00</span></span>
            </div>
            <div class="layui-btn-container" style="text-align: center; margin-top: 20px;">
                <button type="button" class="layui-btn layui-btn-normal" lay-submit lay-filter="confirmBuy">确认购买</button>
                <button type="button" class="layui-btn layui-btn-primary" id="cancelBuy">取消</button>
            </div>
        </form>
    </div>
    <input type="hidden" id="hfContractId" value="@ViewBag.ContractId" />
    <script>
        layui.use(['table', 'form', 'layer'], function () {
            var table = layui.table;
            var form = layui.form;
            var layer = layui.layer;
            var $ = layui.$;
            // 全局存储已选商品（新增）
            var selectedProducts = {}; // 使用对象结构 {id: {productData, quantity}}
            // 初始化表格
            var tableIns = table.render({
                elem: '#productTable',
                defaultToolbar: [],
                url: '/Room/ProductAPI',
                where: {
                    ProductName: '',
                },
                toolbar: '#toolbarDemo',
                page: {
                    limit: 10
                },
                cols: [[
                    { type: 'checkbox', fixed: 'left' },
                    { field: 'Id', title: 'ID', width: 80, hide: true },
                    { field: 'ProductName', title: '产品列表', minWidth: 200 },
                    { field: 'Number', title: '库存数量', width: 120 },
                    {
                        field: 'Price', title: '零售价格', width: 120, templet: function (d) {
                            return '￥' + d.Price.toFixed(2);
                        }
                    }
                ]],
                page: true
            });

            // 搜索功能
            $('#productSearch').on('input', function () {
                var keyword = $(this).val();
                tableIns.reload({
                    where: { // 设置查询参数
                        ProductName: keyword // 将输入的关键字作为参数
                    },
                    page: { // 重置到第一页
                        curr: 1
                    }
                });
            });
            // 计算总价函数（优化）
            function calculateTotal() {
                var total = Object.values(selectedProducts).reduce(function (sum, selected) {
                    // 过滤掉数量<=0的商品（防御性代码）
                    return selected.quantity > 0 ?
                        sum + (selected.product.Price * selected.quantity) :
                        sum;
                }, 0);
                $('#totalPrice').text(total.toFixed(2));
            }
            // 工具栏事件
            table.on('toolbar(productTable)', function (obj) {
                if (obj.event === 'confirm') {
                    var checkData = table.checkStatus('productTable').data;
                    if (checkData.length === 0) {
                        return layer.msg('请先选择商品');
                    }
                    // 合并当前页选中商品到全局存储
                    checkData.forEach(function (item) {
                        if (selectedProducts[item.Id]) {
                            // 已存在则数量+1
                            selectedProducts[item.Id].quantity += 1;
                        } else {
                            // 新商品添加记录
                            selectedProducts[item.Id] = {
                                product: item,
                                quantity: 1 // 初始数量
                            };
                        }
                    });
                    // 生成已选清单
                    var html = '';
                    Object.values(selectedProducts).forEach(function (selected) {
                        var item = selected.product;
                        html += '<tr data-id="' + item.Id + '">' +
                            '<td>' + item.ProductName + '</td>' +
                            '<td>' + item.Number + '</td>' +
                            '<td>' + item.Price.toFixed(2) + '</td>' +
                            '<td><input type="number" class="layui-input quantity" value="' + selected.quantity +
                            '" min="0" max="' + item.Threshold + '"></td>' +
                            '</tr>';
                    });

                    $('#selectedItems').html(html);
                    $('#selectedList').show();
                    form.render();
                    calculateTotal();
                }
            });
            // 数量变化时重新计算总价
            $(document).on('input', '.quantity', function () {
                var $input = $(this);
                var id = $input.closest('tr').data('id');
                var newQuantity = parseInt($input.val()) || 0; // 允许输入0

                // 如果数量<=0则移除商品
                if (newQuantity <= 0) {
                    // 1. 从全局数据移除
                    delete selectedProducts[id];

                    // 2. 从DOM移除
                    $input.closest('tr').remove();

                    // 3. 检查是否还有商品
                    if (Object.keys(selectedProducts).length === 0) {
                        $('#selectedList').hide();
                    }

                    // 4. 显示操作反馈
                    layer.msg('已移除商品', { icon: 1, time: 800 });
                } else {
                    // 正常更新数量
                    if (selectedProducts[id]) {
                        selectedProducts[id].quantity = newQuantity;
                    }
                }
                // 无论是否移除都要重新计算总价
                calculateTotal();
            });
            // 提交购买（修改）
            form.on('submit(confirmBuy)', function () {
                var products = Object.values(selectedProducts).map(function (selected) {
                    return {
                        ProductId: selected.product.Id,
                        ProductName: selected.product.ProductName,
                        Price: selected.product.Price,
                        Quantity: selected.quantity
                    };
                });
                var postData = {
                    Products: products,
                    TotalAmount: parseFloat($('#totalPrice').text()),
                    ContractId: $('#hfContractId').val()
                };

                var loadIndex = layer.load(1);
                $.post("/Room/PruchaseProduct", { productData: JSON.stringify(postData) }, function (resp) {
                    layer.close(loadIndex);
                    if (resp.code == 0) {
                        layer.msg('购买成功', { icon: 1 });
                        // 重置数据（新增）
                        selectedProducts = {};
                        $('#selectedList').hide();
                        $('#selectedItems').empty();
                        $('#totalPrice').text('0.00');
                        table.reload('productTable');
                    } else {
                        layer.msg(resp.msg || '购买失败', { icon: 2 });
                    }
                });
                return false;
            });

            // 取消按钮事件
            $('#cancelBuy').on('click', function () {
                $('#selectedList').hide();
            });
        });
    </script>
</body>
</html>

